<template>
  <div id="brand">
    <div style="margin: 5px; padding: 5px;">
      <el-button type="success" round @click="showAdd">+ 添加</el-button>
    </div>
    <el-input
      v-model="page.searchName"
      placeholder="请输入品牌名称"
      class="demo-form-inline"
    />
    <el-button @click="fetchPage">搜索</el-button>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column label="品牌名称" prop="name" />
      <el-table-column label="品牌图标" prop="logo">
        <template #default="scope">
          <el-image :src="scope.row.logo" style="width: 80px" />
          <!--          头像-->
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" />
      <el-table-column align="center" label="操作">
        <template #default="scope">
          <el-button size="small" @click="showEdit(scope.row)">
            编辑
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--    分页页码-->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="page.pageNum"
        v-model:page-size="page.pageSize"
        :page-sizes="[2, 4, 6, 8]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
        @size-change="fetchPage"
        @current-change="fetchPage"
      />
    </div>

    <!-- 添加\修改用户表单对话框 -->
    <el-dialog v-model="dialogVisible" :title="action" width="30%">
      <el-form label-width="120px">
        <el-form-item label="品牌名称">
          <el-input v-model="brand.name" />
        </el-form-item>
        <el-form-item label="品牌图标">
          <el-upload
            action="http://localhost:8080/admin/product/logoUpload"
            :show-file-list="false"
            :on-success="handleLogoSuccess"
            :headers="header"
          >
            <img v-if="brand.logo" :src="brand.logo" style="width: 80px" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <div v-if="brand.id">
            <el-button type="primary" @click="changeBrand">
              提交
            </el-button>
          </div>
          <div v-else>
            <el-button type="primary" @click="addBrand">提交</el-button>
          </div>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import {
  findBrandsByPage,
  insertBrand,
  updateBrand,
  deleteBrandById,
} from '@/api/brand'
import { useApp } from '@/pinia/modules/app'
import { ElMessage, ElMessageBox } from 'element-plus'

onMounted(async () => {
  await fetchPage()
})

// 删除
const handleDelete = id => {
  ElMessageBox.confirm('此操作将永久删除该记录, 是否继续?', 'Warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const ref = await deleteBrandById(id)
      if (ref.code === 200) {
        ElMessage.success('删除成功')
        fetchPage()
      }
    })
    .catch(() => {
      ElMessage.info('取消删除')
    })
}

const tableData = ref([])
const page = reactive({
  total: '',
  pageNum: 1,
  pageSize: 4,
  searchName: '',
})
const brand = reactive({
  id: '',
  name: '',
  logo: '',
})
// 分页显示数据
const fetchPage = async () => {
  const res = await findBrandsByPage(
    page.pageNum,
    page.pageSize,
    page.searchName
  )
  console.log(page.searchName)
  if (res.code === 200) {
    tableData.value = res.data.records
    page.total = res.data.total
  }
}
const dialogVisible = ref(false)
const action = ref('添加')
// 编辑
const showEdit = row => {
  action.value = '编辑'
  brand.id = row.id
  brand.name = row.name
  brand.logo = row.logo
  dialogVisible.value = true
}
const changeBrand = async () => {
  const res = await updateBrand(brand)
  if (res.code === 200) {
    ElMessage.success('修改成功')
  } else {
    ElMessage.error(res.message)
  }
  dialogVisible.value = false
  fetchPage()
}
// 添加
const showAdd = () => {
  brand.id = ''
  brand.name = ''
  brand.logo = ''
  action.value = '添加'
  dialogVisible.value = true
}
const addBrand = async () => {
  const res = await insertBrand(brand)
  if (res.code === 200) {
    ElMessage.success('添加成功')
  } else {
    ElMessage.error(res.message)
  }
  dialogVisible.value = false
  fetchPage()
}

// 头像
const header = {
  token: useApp().authorization.token,
}
const handleLogoSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  // imageUrl.value = URL.createObjectURL(uploadFile.raw!)

  brand.logo = response.data
}
</script>
<style scoped>
#brand .pagination-container {
  display: flex;
  justify-content: center; /* 水平居中 */
  margin: 20px 0; /* 可选：添加上下间距 */
}
</style>
